import 'dart:ffi';
import 'dart:io';

import 'package:animations/animations.dart';
import 'package:bboy_music_box_2023/bean/bean_music_manager.dart';
import 'package:bboy_music_box_2023/bean/bean_music_query.dart';
import 'package:bboy_music_box_2023/bean/bean_share_file.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_home.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_play.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_query.dart';
import 'package:bboy_music_box_2023/controllers/ctrl_upload.dart';
import 'package:bboy_music_box_2023/custom/view_marquee.dart';
import 'package:bboy_music_box_2023/pages/page_list_select.dart';
import 'package:bboy_music_box_2023/pages/page_list_default.dart';
import 'package:bboy_music_box_2023/pages/page_music.dart';
import 'package:bboy_music_box_2023/pages/page_upload.dart';
import 'package:bboy_music_box_2023/res/colors.dart';
import 'package:bboy_music_box_2023/views/views_container_anim.dart';
import 'package:bboy_music_box_2023/views/views_home.dart';
import 'package:bottom_sheet/bottom_sheet.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late PageController pageController;
  late TabController tabController;

  late AnimationController playAnimController;
  late AnimationController menuAnimController;

  final ContainerTransitionType _transitionType = ContainerTransitionType.fade;

  // 子项集
  late List<Widget> children;

  int initPage = 1;

  MethodChannel platform = MethodChannel('MEventChannel');

  @override
  void initState() {
    super.initState();
    QueryCtrl.to.queryMusics();

    platform.setMethodCallHandler((call) async {
      String method = call.method;
      String arguments = call.arguments;
      print("$method:$arguments");
      if (method == 'receive_file') {
        String shareFileJsonStr = arguments;

        var sharInfo = ShareFileInfo(shareFileJsonStr);
        if ((sharInfo.path ?? "").isNotEmpty) {
          File file = File(sharInfo.path!);
          String path = file.path;
          UploadCtrl.to.fileLive.value = file;
          UploadCtrl.to.fileNameLive.value = sharInfo.name!;
          UploadCtrl.to.filePathLive.value = path;
          UploadCtrl.to.refresh();
          UploadCtrl.to.loadMusic(file);
        }

        print('TEST_SHARE_11111');
        Future.delayed(Duration(milliseconds: 1000), () {
          initPage = 0;
          pageController.jumpToPage(initPage);
          tabController.index = initPage;
        });
      }
      return null;
    });

    playAnimController = AnimationController(vsync: this)
      ..drive(Tween(begin: 0, end: 1))
      ..duration = Duration(milliseconds: 500);

    menuAnimController = AnimationController(vsync: this)
      ..drive(Tween(begin: 0, end: 1))
      ..duration = Duration(milliseconds: 500);

    // 初始化子项集合
    children = [
      UploadView(),
      DefaultListView(),
      SelectListView(),
    ];

    print('TEST_SHARE_22222');
    // 初始化控制器
    pageController = PageController(initialPage: initPage);
    tabController = TabController(
        initialIndex: initPage,
        animationDuration: Duration(milliseconds: 200),
        length: 3,
        vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    print('TEST_SHARE_333333');
    return Material(
      color: Colors.white,
      child: SafeArea(
        child: Scaffold(
          backgroundColor: Colors.white,
          body: Container(
            child: Column(
              children: [
                buildTitleRow(),
                Expanded(
                  child: Stack(
                    children: [
                      Positioned.fill(
                        child: PageView(
                          controller: pageController,
                          // 设置子项集
                          children: children,
                          // 添加页面滑动改变后，去改变索引变量刷新页面来更新底部导航
                          onPageChanged: (value) {
                            HomeCtrl.to.pageIndex.value = value;
                            HomeCtrl.to.pageIndex.refresh();
                            tabController.index = value;
                          },
                        ),
                      ),
                      buildPlayCard(),
                    ],
                  ),
                ),
                buildBottomMenu(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget buildBottomMenu() {
    return Obx(() {
      var pageIndex = HomeCtrl.to.pageIndex.value;
      return Container(
        decoration: BoxDecoration(
            border: Border(top: BorderSide(color: Colors.black87, width: 0.1))),
        padding: const EdgeInsets.symmetric(vertical: 10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child: buildHomeBottomMenuItem(
                Icons.upload,
                '上传',
                pageIndex == 0 ? Colors.deepOrange : Colors.grey,
                onTap: () {
                  HomeCtrl.to.pageIndex.value = 0;
                  HomeCtrl.to.pageIndex.refresh();
                  pageController.jumpToPage(0);
                },
              ),
            ),
            Expanded(
              child: buildHomeBottomMenuItem(
                Icons.play_arrow,
                '音乐',
                pageIndex == 1 ? Colors.deepOrange : Colors.grey,
                onTap: () {
                  HomeCtrl.to.pageIndex.value = 1;
                  HomeCtrl.to.pageIndex.refresh();
                  pageController.jumpToPage(1);
                },
              ),
            ),
            Expanded(
              child: buildHomeBottomMenuItem(
                Icons.menu,
                '管理',
                pageIndex == 2 ? Colors.deepOrange : Colors.grey,
                onTap: () {
                  HomeCtrl.to.pageIndex.value = 2;
                  HomeCtrl.to.pageIndex.refresh();
                  pageController.jumpToPage(2);
                },
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget buildTitleRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          margin: const EdgeInsets.symmetric(vertical: 10.0),
          child: Center(
            child: Text(
              '舞乐',
              style: TextStyle(
                color: Colors.black,
                fontSize: 40.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildPlayCard() {
    return Obx(() {
      MusicManger musicManager = PlayCtrl.to.selectMusic.value;
      bool isSelect = musicManager.music != null;
      return AnimatedPositioned(
        left: 0.0,
        right: 0.0,
        bottom: isSelect ? 0 : -100,
        duration: Duration(milliseconds: 200),
        child: Container(
          color: Colors.white,
          child: isSelect ? playCard(musicManager) : Container(),
        ),
      );
    });
  }

  Widget buildBottomSheet(
    BuildContext context,
    ScrollController scrollController,
    double bottomSheetOffset,
  ) {
    return Material(
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            Row(
              children: [
                Expanded(child: buildPlayCardInSheet()),
              ],
            ),
            Expanded(child: SelectListView()),
          ],
        ),
      ),
    );
  }

  Widget buildPlayCardInSheet() {
    return Obx(() {
      MusicManger musicManager = PlayCtrl.to.selectMusic.value;
      bool isSelect = musicManager.music != null;
      return isSelect ? playCard(musicManager) : Container();
    });
  }

  Widget playCard(MusicManger manger) {
    return Container(
      decoration: BoxDecoration(
          border: Border(top: BorderSide(color: Colors.black87, width: 0.1))),
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      child: Row(
        children: [
          Expanded(
            child: OpenContainerWrapper(
              content: MusicView(),
              transitionType: _transitionType,
              closedBuilder: (context, openContainer) {
                return InkWell(
                  onTap: openContainer,
                  child: buildMusicInfoView(manger),
                );
              },
              onClosed: (bool? isMarkedAsDone) {},
            ),
          ),
          Container(
            width: 40.0,
            height: 40.0,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: Obx(() {
              bool isPlaying = PlayCtrl.to.isPlaying.value;
              isPlaying
                  ? playAnimController.forward()
                  : playAnimController.reverse();
              return InkWell(
                onTap: () {
                  HomeCtrl.to.playAndPause();
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(100.0),
                  ),
                  child: Center(
                    child: AnimatedIcon(
                      color: Colors.white,
                      size: 30.0,
                      icon: AnimatedIcons.play_pause,
                      progress: playAnimController,
                    ),
                  ),
                ),
              );
            }),
          ),
          Container(
            width: 50.0,
            height: 50.0,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: Obx(() {
              bool isSheetShow = HomeCtrl.to.isSheetShow.value;
              isSheetShow
                  ? menuAnimController.forward()
                  : menuAnimController.reverse();
              return InkWell(
                onTap: () {
                  if (!HomeCtrl.to.isSheetShow.value) {
                    HomeCtrl.to.isSheetShow.value = true;
                    HomeCtrl.to.isSheetShow.refresh();
                    showFlexibleBottomSheet(
                      minHeight: 0,
                      initHeight: 0.8,
                      maxHeight: 0.8,
                      context: context,
                      builder: buildBottomSheet,
                      isExpand: false,
                      bottomSheetBorderRadius: BorderRadius.circular(20.0),
                    ).then((value) {
                      HomeCtrl.to.isSheetShow.value = false;
                      HomeCtrl.to.isSheetShow.refresh();
                    });
                  } else {
                    HomeCtrl.to.isSheetShow.value = false;
                    HomeCtrl.to.isSheetShow.refresh();
                    Get.back();
                  }
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100.0),
                  ),
                  child: Center(
                    child: AnimatedIcon(
                      color: Colors.grey,
                      size: 30.0,
                      icon: AnimatedIcons.menu_close,
                      progress: menuAnimController,
                    ),
                  ),
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  Widget buildMusicInfoView(MusicManger manger) {
    return Row(
      children: [
        Container(
          width: 30.0,
          height: 30.0,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5.0),
          ),
          child: Image.network(manger.music!.imgUrl),
        ),
        Expanded(
          child: Container(
            child: ListTile(
              title: Container(
                child: Text(
                  manger.music!.name,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 14.0,
                  ),
                  textAlign: TextAlign.left,
                  maxLines: 1,
                  softWrap: false,
                  overflow: TextOverflow.fade,
                ),
              ),
              subtitle: Container(
                child: Text(
                  '${(manger.seek ~/ 60).toString().padLeft(2, '0')}'
                  ':${(manger.seek % 60).toString().padLeft(2, '0')}/'
                  '${(manger.duration ~/ 60).toString().padLeft(2, '0')}'
                  ':${(manger.duration % 60).toString().padLeft(2, '0')}',
                  style: const TextStyle(
                    fontSize: 8.0,
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  void playAndPause() async {
    Music? music = PlayCtrl.to.selectMusic.value.music;
    if (music == null) return;
    await PlayCtrl.to.playOrPause(music);
  }
}
